import React, { useState, useEffect } from 'react';
import lodash from 'lodash';
import { Select, Spin, Empty } from 'antd';
import { delectProps } from '../utils';
import { connect } from 'umi';
import debounce from 'lodash/debounce';
import { useUpdateEffect } from 'ahooks'
const SelectBlock = (props) => {
    const {
        type,
        select,
        label: plabel,
        suffix,
        loading,
        placeholder,
        fieldNames = {},
        onchange,
        dispatch,
        params = {},
        defaultData
    } = props;

    const divProps = delectProps(props);
    const { label = 'teacherName', value = 'id', tip = 'otherData' } = fieldNames;
    const [searchData, changeSearchData] = useState({
        pagination: {
            page: 1,
            limit: 30
        },
        keyword: ''
    })
    const [option, setOption] = useState(defaultData ? [defaultData] : [])
    const { pagination: { page, limit }, keyword } = searchData
    const scrollEnd = (e) => {
        e.persist();
        const { target } = e;
        // 滚动 触底 看接口是否还有剩余的值没传过来
        console.log(target.scrollTop, target.offsetHeight, target.scrollHeight)
        if (parseInt(target.scrollTop + target.offsetHeight + 1) >= target.scrollHeight) {
            changeSearchData({
                ...searchData,
                pagination: {
                    ...searchData.pagination,
                    page: page + 1
                },
            })
        }
    }
    const fetchGetUser = debounce((reload) => {
        if (reload) {
            dispatch({
                type: 'selectionWindow/fetchListTeacher',
                payload: {
                    ...params,
                    page, limit, keyword
                },
                callback: (e, total) => {
                    setOption(e)
                }
            });
        }
        else {
            dispatch({
                type: 'selectionWindow/fetchListTeacher',
                payload: {
                    ...params,
                    page, limit, keyword
                },
                callback: (e, total) => {
                    if (defaultData) {
                        setOption([...option, ...e.filter(val => {
                            return val[value] !== defaultData[value]
                        })])
                    }
                    else {
                        setOption([...option, ...e])
                    }

                }
            });
        }
    }, 500);
    useEffect(() => {
        fetchGetUser()
    }, [page])
    useUpdateEffect(() => {
        console.log('更新了', keyword)
        // setOption(() => {
        //   return []
        // })
        fetchGetUser(true)
    }, [keyword])
    // 遍历对象
    const arrObject = (obj) => {
        return Object.keys(obj).map((item) => ({
            [label]: obj[item],
            [value]: item,
        }));
    };

    /**
     *  判断传入select 类型
     *  [] | {}
     */
    let selectList = [];
    if (Array.isArray(select)) {
        selectList = select;
    } else if (lodash.isPlainObject(select)) {
        // 若为对象则将遍历成数组赋值
        selectList = arrObject(select);
    }

    // type === tags 配置
    let multProps = {};
    if (type === 'tags') multProps = { mode: 'tags', tokenSeparators: [',', '，'] };
    // type === multiple 配置
    if (type === 'multiple') multProps = { mode: 'multiple', tokenSeparators: [',', '，'] };
    console.log(selectList, 'list')
    return (
        <>
            <Select
                showSearch
                style={{ width: suffix ? '75%' : '100%' }}
                optionFilterProp="children"
                onPopupScroll={scrollEnd}
                notFoundContent={
                    loading ? <Spin size="small" /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                }
                loading={loading}
                filterOption={() => { return true }}
                onChange={(e) => {
                    console.log(e);
                }}
                onSearch={(val) => {
                    console.log(val)
                    changeSearchData({
                        pagination: {
                            ...searchData.pagination,
                            page: 1
                        },
                        keyword: val
                    })
                }}
                {...multProps}
                {...divProps}
                placeholder={placeholder || `请选择${plabel}`}
            >
                {option.map((data, j) => {
                    if (data) {
                        const nameD = data[label];
                        // 兼容数组
                        const valueData = !data[value] ? `${j}` : data[value];
                        const nameData = nameD ? nameD : typeof data == 'string' ? data : '--';
                        const otherData = data[tip] ? data[tip] : '';
                        return (
                            <Select.Option
                                key={data[value] || j}
                                disabled={data.disabled || false}
                                value={valueData}
                                option={data}
                            >
                                {nameData}
                                {otherData && <div style={{ fontSize: 12, color: '#989898' }}>{otherData}</div>}
                            </Select.Option>
                        );
                    }
                })}
            </Select>
            {suffix && <span style={{ marginLeft: 10 }}>{suffix}</span>}
        </>
    );
};
export default connect(({ loading }) => ({
    loading: loading.effects['selectionWindow/fetchListTeacher'],
}))(SelectBlock);

